<template>
  <div>
    <h1 class="title">商品列表</h1>
    <p>{{$store.state.username}}</p>
    <p>{{$store.getters.getTotalPrice}}</p>
    <p>年龄：{{$store.state.age}}</p>
    <button @click="setAge">点击长大</button>
    <p>数字：{{$store.state.num}}</p>
    <button @click="setNum(newVal)">点击修改</button>
    <div v-for="(phone, index) in goods" :key="phone.id">
        <!-- to本来的样子：:to="'/productDetail/'+phone.id+'/'+phone.name+'/'+phone.price" -->
      <router-link 
        :to="{
          name: 'productDetail',
          params: {
            id: phone.id,
            name: phone.name,
            price: phone.price
          }
        }"
      >
        {{index+1}}. {{phone.name}}
      </router-link>
      <button @click="change">jump</button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      newVal: 666,
      goods: [
        {
          name: 'iphone 12',
          price: 8999,
          id: '1234ljkhkjlq2h3'
        },
        {
          name: 'mi 10',
          price: 4999,
          id: '1dfg34ljkhkjlq2h3'
        },
        {
          name: 'hauwei p40',
          price: 5999,
          id: 'hw1p4ljkhkjlq2h3'
        }
      ]
    };
  },
  components: {
    
  },
  methods: {
    change() {
      // 命名路由：使用name，代替长长的path
      this.$router.push({
        name: 'productDetail',
        params: {
          id: 1,
          name: 2,
          price: 400
        }
      })
    },
    setAge() {
      // 最简单的方式
      // 通过vuex中的mutations修改年龄,通过commit来触发mutations中的内容
      this.$store.commit('setAge');
    },
    setMsg() {
      // 比较复杂的方式，需要在commit中传值。要明白值是怎么来的
      let newMsg = 'hello'
      this.$store.commit('setAge', newMsg);
    },
    setNum(newVal) {
      // 最复杂的方式
      // 以下是对象风格的提交方式，所有的数据都打包放在payload中
      this.$store.commit({
        type: 'setNum',
        newVal: newVal,
        newNewVal: 777
      })
    }
  },
};
</script>
<style lang="stylus">
  colorRed = red
  .title
  a
    color colorRed
</style>